package com.lancoo.answer.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Created by pengmi on 2021/12/9 10:15
 * Description:wav音频拼接处理工具
 */
public class WavAppendUtils {

    public static final int BUFFER_SIZE = 1024 * 50;
    public static final int WAV_HEAD_TOTAL_LENGTH = 44;// 44字节

    /**
     * 将新音频拼接在旧音频上
     *
     * @param old 旧音频
     * @param now 新音频
     * @return
     */
    public static boolean appendWav(File old, File now) {
        if (!old.exists() || old.length() <= 0 || !now.exists() || now.length() <= 0) {
            return false;
        }

        boolean isOk = true;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(now);
            fos = new FileOutputStream(old, true);
            boolean hasHead = true;
            byte[] buffer = new byte[BUFFER_SIZE];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                if (hasHead) {
                    hasHead = false;
                    fos.write(buffer, WAV_HEAD_TOTAL_LENGTH, len - WAV_HEAD_TOTAL_LENGTH);
                } else {
                    fos.write(buffer, 0, len);
                }
            }
            fos.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            isOk = false;
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (isOk) updateWavHead(old);
        }
        return false;
    }

    private static void updateWavHead(File file) {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "rw");
            raf.seek(4L);
            raf.writeInt(Integer.reverseBytes((int) (file.length() - 8L)));
            raf.seek(40L);
            raf.writeInt(Integer.reverseBytes((int) (file.length() - 44L)));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
